// src/pages/goods/goods.vue
<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { computed, reactive } from 'vue'
import { getProductDetailAPI } from '@/services/goodsApi'
import { BaseUrl } from '@/utils/request'
import { addCartApi } from '@/services/cartAPI'
import { ref } from 'vue'
import type { ProductType } from '@/types/home'
import addressP from './componments/addressP.vue'
import service from './componments/service.vue'
import type { addressType } from '@/types/productDetai'
import { getAddressListAPI } from '@/services/goodsApi'
import { getSkuListApi } from '@/services/skuAPI'
import { useCartStore } from '@/stores/modules/CartStore'
import type { sku_data_item } from '@/types/sku'
import type { SkuPopupEvent } from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
// sku组件弹出层实例类型
import type { SkuPopupInstanceType } from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
import VkDataGoodsSkuPopup from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup.vue'
const goodsInfo = ref<sku_data_item>({} as sku_data_item)
const addressList = ref<addressType[]>()
// sku组件提供了三个选择模式，分别是如下三种，通过这三种模式可以控制按钮的显示与隐藏
enum skuModeType {
  boht = 1,
  cart = 2,
  Buy = 3,
}
const skuMode = ref<skuModeType>(skuModeType.boht)

// sku显示隐藏
const skuKey = ref(false)
const getSkuInfo = async (good_id: number) => {
  const res = await getSkuListApi(good_id)
  if (res!.data!.sku_list.length > 0) {
    for (let i = 0; i < res!.data!.sku_list?.length; i++) {
      res!.data!.sku_list[i].price = res!.data!.sku_list[i]!.price! * 100
    }
  }
  return res
}
// 获取地址数据传递给子组件
const getAddressData = async () => {
  const res = await getAddressListAPI()
  if (res.statusCode != 200) {
    componentType.value = ''
  }
  addressList.value = res.data
}

const params = defineProps<{ goods_id: number }>()
// 获取屏幕边界到安全区域距离
const systemInfo = reactive({
  safeAreaInsets: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
  },
})
//具体的弹出框
const componentType = ref('')
// vue3模板中使用ref定义的变量，在script中可以直接接收到
const popup = ref<{ open: (type?: UniHelper.UniPopupType) => void; close: () => void }>()
// 关闭弹出框
const closePopup = () => {
  componentType.value = ''
  popup.value?.close()
}
const current = ref(0)
const productDetail = ref<ProductType>()
const getProductDetail = async (id: number) => {
  const res = await getProductDetailAPI(id)
  productDetail.value = res.data
}
// 图片预览
const tapPreviewImage = (index: number) => {
  const urls = productDetail?.value?.images?.map((item) => {
    console.log(`${BaseUrl}/${item.image}`)
    return `${BaseUrl}/${item.image}`
  })
  uni.previewImage({
    current: index,
    urls: urls!,
  })
  console.log('执行预览')
}
// 图片下标
const swiperOnChange = (e: UniHelper.SwiperOnChangeEvent) => {
  current.value = e.detail.current
}
onLoad(async () => {
  const info = await uni.getSystemInfoSync()
  await getProductDetail(params.goods_id)
  systemInfo.safeAreaInsets = info.safeAreaInsets!
})

const showPopup = async (type: string) => {
  if (type === 'specification') {
    componentType.value = 'specification'
  } else if (type === 'address') {
    await getAddressData()
    componentType.value = 'address'
    await getAddressData()
  } else if (type === 'service') {
    componentType.value = 'service'
  }
  popup.value?.open('bottom')
}
// 打开sku组件
// 组件提供了三种选择模式，分别是如下三种，通过这三种模式可以控制按钮的具体显示，
const onOpenSkuPopup = async (val: skuModeType) => {
  skuMode.value = val
  const res = await getSkuInfo(params.goods_id)
  goodsInfo.value = res.data as sku_data_item
  // 个别商品商品我后端没有做规格，只有一个默认，所以需要判断一下,没有sku的情况下直接添加或进入订单页
  if (res.data?.spec_list.length === 0) {
    const sku_id = goodsInfo.value!.sku_list[0]._id
    const buy_num = 1
    const data = { num: buy_num, sku_id: sku_id }
    if (val === skuModeType.cart) {
      const res = await addCartApi(data)
      if (res.code === 200) {
        uni.showToast({
          title: '已添加到购物车',
          icon: 'success',
          duration: 2000,
        })
      } else {
        uni.showToast({
          title: '添加失败',
          icon: 'fail',
          duration: 2000,
        })
      }
    } else if (val === skuModeType.Buy) {
      uni.navigateTo({
        url: '/pages/order/order?sku_id_list=' + JSON.stringify([sku_id]) + '&&num=' + 1,
      })
    }
    return
  }
  skuKey.value = true
}

// 通过ref获取到组件实例
const skuPopupRef = ref<SkuPopupInstanceType>()
// 计算属性  selectArr是组件实例选择的sku选项内容
const optionValue = computed(() => {
  if (productDetail.value?.has_attr) {
    // 因为取消选中的属性，selectArr这个列表中的元素会变为' ',把多个' '拼接起来就变成了'   '
    // 所以需要去除空格，这样就变为了空，从而执行另一个
    return skuPopupRef.value?.selectArr?.join(' ').trim() || '请选择商品属性'
  } else {
    return '该商品无属性'
  }
})
// const addressText=computed(()=>{

// })
// 加入购物车按钮,sku组件提供的接口
const onAddCart = async (event: SkuPopupEvent) => {
  if (event._id && event.buy_num) {
    const data = { num: event.buy_num, sku_id: event._id }
    const res = await addCartApi(data)
    if (res.code === 200) {
      uni.showToast({
        title: '操作成功',
        icon: 'success',
        duration: 2000,
      })
    }
  }
}
// 插件购买按钮
const onBuyNow = async (event: SkuPopupEvent) => {
  if (event._id && event.buy_num) {
    const data = { num: event.buy_num, sku_id: event._id, sku_name_arr: event.sku_name_arr }
    // cartStore.clear_settle_order()
    console.log(data)
    uni.navigateTo({
      url: `/pages/order/order?sku_id_list=${JSON.stringify([event._id])}&&num=${event.buy_num}`,
    })
  }
}
</script>

<template>
  <scroll-view scroll-y class="viewport" v-if="productDetail">
    <!-- 基本信息 -->
    <view class="goods">
      <!-- 商品主图 -->
      <view class="preview">
        <swiper circular @change="swiperOnChange">
          <swiper-item v-for="(image, index) in productDetail?.images" :key="image.image">
            <image
              mode="aspectFill"
              :src="`${BaseUrl}/${image.image}`"
              @tap="tapPreviewImage(index)"
            />
          </swiper-item>
        </swiper>
        <view class="indicator">
          <text class="current">{{ current + 1 }}</text>
          <text class="split">/</text>
          <text class="total">{{ productDetail?.images?.length }}</text>
        </view>
      </view>

      <!-- 商品简介 -->
      <view class="meta">
        <view class="price">
          <text class="symbol">¥</text>
          <text class="number">{{ productDetail?.current_price }}</text>
        </view>
        <view class="name ellipsis"> </view>
        <view class="desc">{{ productDetail?.description }} </view>
      </view>

      <!-- 操作面板 -->
      <view class="action">
        <view
          v-if="productDetail?.has_attr"
          class="item arrow"
          @tap="onOpenSkuPopup(skuModeType.boht)"
        >
          <text class="label">选择</text>
          <text class="text ellipsis"> {{ optionValue }} </text>
        </view>
        <view v-else class="item arrow">
          <text class="label">默认</text>
          <text class="text ellipsis"> 该商品无属性 </text>
          <text class="label">库存</text>
          <text class="text ellipsis"> {{ productDetail?.stock }} </text>
        </view>
        <view class="item arrow" @tap="showPopup('address')">
          <text class="label">送至</text>
          <text class="text ellipsis"> 请选择收获地址 </text>
        </view>
        <view class="item arrow" @tap="showPopup('service')">
          <text class="label">服务</text>
          <text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail panel">
      <view class="title">
        <text>详情</text>
      </view>
      <view class="content">
        <view class="properties">
          <!-- 属性详情 -->
          <view class="item">
            <text class="label">属性名</text>
            <text class="value">属性值</text>
          </view>
          <view class="item">
            <text class="label">属性名</text>
            <text class="value">属性值</text>
          </view>
        </view>
        <!-- 图片详情 -->
        <image
          mode="widthFix"
          src="https://yanxuan-item.nosdn.127.net/a8d266886d31f6eb0d7333c815769305.jpg"
        ></image>
        <image
          mode="widthFix"
          src="https://yanxuan-item.nosdn.127.net/a9bee1cb53d72e6cdcda210071cbd46a.jpg"
        ></image>
      </view>
    </view>

    <!-- 同类推荐 -->
    <view class="similar panel">
      <view class="title">
        <text>同类推荐</text>
      </view>
      <view class="content">
        <navigator
          v-for="item in 4"
          :key="item"
          class="goods"
          hover-class="none"
          :url="`/pages/goods/goods?id=`"
        >
          <image
            class="image"
            mode="aspectFill"
            src="https://yanxuan-item.nosdn.127.net/e0cea368f41da1587b3b7fc523f169d7.png"
          ></image>
          <view class="name ellipsis">{{ productDetail?.name }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ productDetail.current_price }}</text>
          </view>
        </navigator>
      </view>
    </view>
  </scroll-view>
  <!-- SKU -->
  <view class="app">
    <VkDataGoodsSkuPopup
      ref="skuPopupRef"
      v-model="skuKey"
      border-radius="20"
      :z-index="10000"
      :localdata="goodsInfo"
      :mode="skuMode"
      buyNowBackgroundColor="#f5342a"
      addCartBackgroundColor="#FF9402"
      @add-cart="onAddCart"
      @buy-now="onBuyNow"
    ></VkDataGoodsSkuPopup>
  </view>

  <!-- 用户操作 -->
  <view
    :class="componentType ? 'display-none' : 'toolbar'"
    :style="{ paddingBottom: systemInfo.safeAreaInsets?.bottom + 'px' }"
  >
    <view class="icons">
      <button class="icons-button"><text class="icon-heart"></text>收藏</button>
      <button class="icons-button" open-type="contact">
        <text class="icon-handset"></text>客服
      </button>
      <!-- 注意这里有一个大坑，购物车页面是tabBar页，会关闭所有非tabBar的其他页面，
       所以小程序的tabBar页没有后退按钮，解决方案是新建一个普通购物车页面， 指定 open-type="switchTab"-->
      <!-- navigateTo：保留当前页面，跳转到应用内的某个页面。
        使用 navigateBack 可以返回到原页面 -->
      <!-- redirectTo：关闭当前页面，跳转到应用内的某个页面。
         没有后退按钮，但可以使用 navigateBack 返回到上一个页面 -->
      <navigator class="icons-button" url="/pages/cart/cart2" open-type="navigateTo">
        <text class="icon-cart"></text>购物车
      </navigator>
    </view>
    <view class="buttons">
      <!-- 点击加入购物车的时候触发sku组件 -->
      <view class="addcart" @tap="onOpenSkuPopup(skuModeType.cart)"> 加入购物车 </view>
      <view class="buynow" @tap="onOpenSkuPopup(skuModeType.Buy)"> 立即购买 </view>
    </view>
  </view>
  <uni-popup ref="popup" type="buttom">
    <service v-if="componentType === 'service'" @close="closePopup"></service>
    <addressP v-if="componentType === 'address'" :list="addressList" @close="closePopup"></addressP>
  </uni-popup>
</template>

<style lang="scss" scoped>
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.viewport {
  background-color: #f4f4f4;
}

.panel {
  margin-top: 20rpx;
  background-color: #fff;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 90rpx;
    line-height: 1;
    padding: 30rpx 60rpx 30rpx 6rpx;
    position: relative;
    text {
      padding-left: 10rpx;
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      border-left: 4rpx solid #27ba9b;
    }
    navigator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.arrow {
  &::after {
    position: absolute;
    top: 50%;
    right: 30rpx;
    content: '\e6c2';
    color: #ccc;
    font-family: 'erabbit' !important;
    font-size: 32rpx;
    transform: translateY(-50%);
  }
}

/* 商品信息 */
.goods {
  background-color: #fff;
  .preview {
    height: 750rpx;
    position: relative;
    .indicator {
      height: 40rpx;
      padding: 0 24rpx;
      line-height: 40rpx;
      border-radius: 30rpx;
      color: #fff;
      font-family: Arial, Helvetica, sans-serif;
      background-color: rgba(0, 0, 0, 0.3);
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;
      .current {
        font-size: 26rpx;
      }
      .split {
        font-size: 24rpx;
        margin: 0 1rpx 0 2rpx;
      }
      .total {
        font-size: 24rpx;
      }
    }
  }
  .meta {
    position: relative;
    border-bottom: 1rpx solid #eaeaea;
    .price {
      height: 130rpx;
      padding: 25rpx 30rpx 0;
      color: #fff;
      font-size: 34rpx;
      box-sizing: border-box;
      background-color: #35c8a9;
    }
    .number {
      font-size: 56rpx;
    }
    .brand {
      width: 160rpx;
      height: 80rpx;
      overflow: hidden;
      position: absolute;
      top: 26rpx;
      right: 30rpx;
    }
    .name {
      max-height: 88rpx;
      line-height: 1.4;
      margin: 20rpx;
      font-size: 32rpx;
      color: #333;
    }
    .desc {
      line-height: 1;
      padding: 0 20rpx 30rpx;
      font-size: 24rpx;
      color: #cf4444;
    }
  }
  .action {
    padding-left: 20rpx;
    .item {
      height: 90rpx;
      padding-right: 60rpx;
      border-bottom: 1rpx solid #eaeaea;
      font-size: 26rpx;
      color: #333;
      position: relative;
      display: flex;
      align-items: center;
      &:last-child {
        border-bottom: 0 none;
      }
    }
    .label {
      width: 60rpx;
      color: #898b94;
      margin: 0 16rpx 0 10rpx;
    }
    .text {
      flex: 1;
      -webkit-line-clamp: 1;
    }
  }
}

/* 商品详情 */
.detail {
  padding-left: 20rpx;
  .content {
    margin-left: -20rpx;
  }
  .properties {
    padding: 0 20rpx;
    margin-bottom: 30rpx;
    .item {
      display: flex;
      line-height: 2;
      padding: 10rpx;
      font-size: 26rpx;
      color: #333;
      border-bottom: 1rpx dashed #ccc;
    }
    .label {
      width: 200rpx;
    }
    .value {
      flex: 1;
    }
  }
}

/* 同类推荐 */
.similar {
  padding-left: 20rpx;
  .content {
    padding: 0 20rpx 20rpx;
    margin-left: -20rpx;
    background-color: #f4f4f4;
    overflow: hidden;
    navigator {
      width: 345rpx;
      padding: 24rpx 20rpx 20rpx;
      margin: 20rpx 20rpx 0 0;
      border-radius: 10rpx;
      background-color: #fff;
      float: left;
    }
    .image {
      height: 260rpx;
    }
    .name {
      height: 80rpx;
      margin: 10rpx 0;
      font-size: 26rpx;
      color: #262626;
    }
    .price {
      line-height: 1;
      font-size: 20rpx;
      color: #cf4444;
    }
    .number {
      font-size: 26rpx;
      margin-left: 2rpx;
    }
  }
  navigator {
    &:nth-child(even) {
      margin-right: 0;
    }
  }
}

/* 底部工具栏 */
.toolbar {
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  // 固定定位，当页面滚动时，固定在底部，position: sticky;
  //  需要至少指定一个 top、right、bottom 或 left 属性才能生效。在代码中，bottom: 0; 已经指定了元素在滚动到页面底部时的固定位置。
  // position: sticky; 在某些旧版本的浏览器中可能不支持，可以使用浏览器前缀或其他替代方案来确保兼容性。
  position: sticky;
  bottom: 0;
  z-index: 100;
  .buttons {
    display: flex;
    & > view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }
    .addcart {
      background-color: #ff9402;
    }
    .buynow {
      background-color: #f5342a;
      margin-left: 20rpx;
    }
  }
  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;
    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;
    }
    text {
      display: block;
      font-size: 34rpx;
    }
  }
}
.display-none {
  display: none;
}
</style>
